﻿using Guoc.BigMall.Infrastructure.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure.Utils;
using Dapper.DBContext;
using Guoc.BigMall.Infrastructure.Log;
using Guoc.BigMall.Infrastructure.Extension;
using System.Net.NetworkInformation;

namespace Guoc.BigMall.WebService.Event
{
    public class SaleOrderPaidEventHandler : IConsumer<SaleOrderPaidEvent>
    {
        ISequence _idSequence;
        IDBContext _db;
        int _MaxLevel = 7;
        ILogger _log;
        public SaleOrderPaidEventHandler(ISequence idSequence, IDBContext db, ILogger log)
        {
            _idSequence = idSequence;
            _db = db;
            _log = log;
        }

        public void HandleEvent(SaleOrderPaidEvent eventMessage)
        {
            _log.Info("开始处理分账事件");
            var order = eventMessage.Order;
            _log.Info("处理订单：{0}",order.Code);
            var entity = _db.Table<DistributeOrder>().FirstOrDefault(n => n.SaleOrderCode == order.Code);
            if (entity == null) {
                _log.Info("订单对应的{0}分销单不存在。", order.Code);
                _log.Info("结束处理分账事件");
                return;
            }
            var infoCheck = "";
            if (string.IsNullOrEmpty(entity.MemberPhone)) infoCheck += "开卡号码为空!";
            if (string.IsNullOrEmpty(entity.MemberName)) infoCheck += "真实姓名为空";
            if (string.IsNullOrEmpty(entity.ContactPhone)) infoCheck += "联系电话为空";
            if (string.IsNullOrEmpty(entity.IdentityCard)) infoCheck += "身份证为空";
            if (!string.IsNullOrEmpty(infoCheck)) {
                var reason = infoCheck;
                CancelDistributeOrder(entity, reason);
                return;
            }

            if (order.MemberId == order.ReferMemberId) {
                var reason = string.Format("不能自己推荐自己下单");
                CancelDistributeOrder(entity, reason);
                return;
            }
            //检查下单手机号码是否已经是分销会员
            if (_db.Table<DistributeMember>().Exists(n => n.Phone == entity.MemberPhone))
            {
                var reason = string.Format("号码{0},已经办理过", entity.MemberPhone);
                CancelDistributeOrder(entity, reason);
                return;
            }
            // 检查推荐人是否分销会员ReferMemberId
            var parentMember = _db.Table<DistributeMember>().FirstOrDefault(n => n.MemberId == entity.ReferMemberId);
            if (parentMember == null)
            {
                var reason = string.Format("订单[{0}]没有推荐人", order.Code);
                CancelDistributeOrder(entity, reason);
                return;
            }

            //创建 分销订单,必须是待审才行
            entity.SaleOrderId = order.Id;
            entity.WaitAudit();
            //创建提现明细
            var products = _db.Table<SaleOrderItem>().Where(n => n.SaleOrderId == entity.SaleOrderId).Select(n => n.ProductId).ToList().ToArray();
            var productRebets = _db.Table<DistributeRebate>().Where(n => n.ProductId.In(products)).ToList();
            foreach (var pid in products)
            {
                // 创建多级分账明细
                var levelMeberArray = parentMember.Path.Trim('#').Split('#').ToList();
                levelMeberArray.Reverse();
                for (var i = 0; i < levelMeberArray.Count(); i++)
                {
                    if (i < _MaxLevel)
                    {
                        var mebid = int.Parse(levelMeberArray[i]);
                        var productRebet = productRebets.FirstOrDefault(n => n.ProductId == pid && n.Level == i + 1);
                        if (productRebet == null || productRebet.LevelRebate <= 0)
                        {
                            _log.Info(" Warring:{0}商品还没配置分账金额参数。", pid);
                            continue;
                        }
                        DistributeOrderItem item = new DistributeOrderItem()
                        {
                            DistributeOrderId = entity.Id,
                            MemberId = mebid,
                            ProfitAmount = productRebet.LevelRebate,
                            ProfitLevel = i + 1,  // 1级                                  
                        };

                        entity.Items.Add(item);
                        _log.Info(":销售单{0}=> 返利会员{1}，{2}级返利，金额={3}", order.Code, mebid, item.ProfitLevel, item.ProfitAmount);
                    }
                }
            }
            // 记录分销单历史
            DistributeOrderHistory auditHistory = new DistributeOrderHistory()
            {
                Createdby = 1,
                CreatedbyName = "系统",
                DistributeOrderId = entity.Id,
                Remark = entity.Status.Description(),
                Status = entity.Status
            };
           

            _db.Insert(auditHistory);
            _db.Update(entity);
            _db.Insert(entity.Items.ToArray());
            _db.SaveChange();
            _log.Info("结束处理分账事件");
            _log.Info("----------------end------------------");
        }

        public void CancelDistributeOrder(DistributeOrder distributeOrder,string reason) {
            distributeOrder.Status = DistributeOrderStatus.Cancel;
            DistributeOrderHistory history = new DistributeOrderHistory()
            {
                Createdby = 1,
                DistributeOrderId = distributeOrder.Id,
                CreatedbyName = "系统",
                Remark = reason ,
                Status = DistributeOrderStatus.Cancel
            };
            _db.Update(distributeOrder);
            _db.Insert(history);
            _db.SaveChange();
            _log.Info(reason);
            _log.Info("结束处理分账事件");
            _log.Info("----------------end------------------");
        }

    }
}
